from django.shortcuts import render

# Create your views here.
from django.views import View
from django.http import HttpResponse
from django_redis import get_redis_connection
from meiduo_mall.libs.captcha.captcha import captcha
from celery_tasks.sms.tasks import ccp_send_sms_code


class ImageCodeView(View):
    '''返回图形验证码的类视图'''

    def get(self, request, uuid):
        text, image = captcha.generate_captcha()

        redis_conn = get_redis_connection('verify_code')
        redis_conn.setex('img_%s' % uuid, 300, text)

        return HttpResponse(image, content_type='image/jpg')


import logging

logger = logging.getLogger('django')
import random
from django import http
from meiduo_mall.libs.yuntongxun.ccp_sms import CCP


class SMSCodeView(View):
    def get(self, request, mobile):

        redis_conn = get_redis_connection('verify_code')

        send_flag = redis_conn.get('send_flag_%s' % mobile)

        if send_flag:
            return http.JsonResponse({
                'code': 400,
                'errmsg': '短信发送过于频繁'
            })

        image_code_client = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')

        if not all([image_code_client, uuid]):
            return http.JsonResponse({
                'code': 400,
                'errmsg': '缺少必传参数'
            })

        image_code_server = redis_conn.get('img_%s' % uuid)

        if image_code_server is None:
            return http.JsonResponse({
                'code': 400,
                'errmsg': '图形验证码失效'
            })
        try:
            redis_conn.delete('img_%s' % uuid)

        except Exception as e:
            logger.error(e)

        image_code_server = image_code_server.decode()

        if image_code_client.lower() != image_code_server.lower():
            return http.JsonResponse({
                'code': 400,
                'errmsg': '图形验证码错误'
            })
        sms_code = '%06d' % random.randint(0, 999999)
        logger.info(sms_code)

        pl = redis_conn.pipeline()

        pl.setex('sms_%s' % mobile, 300, sms_code)
        pl.setex('send_flag_%s' % mobile, 60, 1)

        pl.execute()

        # CCP.send_template_sms(mobile, [sms_code, 5], 1)
        # ccp_send_sms_code.delay(mobile, sms_code)

        return http.JsonResponse({
            'code': 0,
            'errmsg': '发送短信成功'
        })
